package dk.twu.analyzer.loader;

import dk.twu.analyzer.model.Exchange;
import dk.twu.analyzer.util.AnalyzerConfig;

import java.io.File;
import java.io.FilenameFilter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

public class MarketDataHelper {
    public static final String C_ITD_FOLDER = "1";
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static File[] getFilesForExchange(AnalyzerConfig config, DataType type, Exchange exchange,
                                             Optional<LocalDate> fromDate, Optional<LocalDate> toDate) {
        File baseDir = DataType.ITD.equals(type) ? new File(config.getBaseDir() + exchange.getCode() + "\\" +
                C_ITD_FOLDER) : new File(config.getBaseDir() + exchange.getCode());
        if (baseDir.exists()) {
            return baseDir.listFiles(new CSVFileFilter(fromDate, toDate));
        } else {
            return new File[0];
        }
    }

    public static enum DataType {ITD, EOD}

    private static class CSVFileFilter implements FilenameFilter {
        private final Optional<LocalDate> fromDate;
        private final Optional<LocalDate> toDate;

        public CSVFileFilter(Optional<LocalDate> fromDate, Optional<LocalDate> toDate) {
            this.fromDate = fromDate;
            this.toDate = toDate;
        }

        @Override
        public boolean accept(File dir, String name) {
            String text = name.replaceAll("\\D+", "");
            if ((text == null) || (text.length() == 0) || text.equals(C_ITD_FOLDER)) return false;
            LocalDate date = LocalDate.parse(text, DATE_FORMATTER);
            if (!name.endsWith(".csv")) return false;
            else if (fromDate.isPresent() && date.compareTo(fromDate.get()) < 0) return false;
            else if (toDate.isPresent() && date.compareTo(toDate.get()) > 0) return false;
            else return true;
        }
    }

}
